package cn.myfirefly.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

/**
 * 用于将结果集转换为html
 * 
 * @author zhouxiaoming
 */
public class HtmlTemplateUtil {
//	private static Logger logger = LoggerFactory.getLogger(HtmlTemplateUtil.class);
	
	private static final String DEFAULT_HTML_PATH = "/";
	
	public static String getHtml(List<Object> results, String templatePath, String templateName) {
		// 初始化模板绝对路径
		Properties p = new Properties();
		p.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, templatePath);
		Velocity.init(p);
		//封装模板数据
		Map<String, Object> map = new HashMap<>();
		map.put("results", results);
		VelocityContext context = new VelocityContext(map);
		//渲染模板
		StringWriter sw = new StringWriter();
		Template tpl = Velocity.getTemplate(templateName+".vm", "UTF-8");
		tpl.merge(context, sw);
		return sw.toString();
	}
	
	public static String getHtml(Map<String, Object> results, String templatePath, String templateName) {
		// 初始化模板绝对路径
		Properties p = new Properties();
		p.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, templatePath);
		Velocity.init(p);
		//封装模板数据
		Map<String, Object> map = new HashMap<>();
		map.put("result", results);
		VelocityContext context = new VelocityContext(map);
		//渲染模板
		StringWriter sw = new StringWriter();
		Template tpl = Velocity.getTemplate(templateName+".vm", "UTF-8");
		tpl.merge(context, sw);
		return sw.toString();
	}
	
	public static String toHtml(String html, String realPath, String templateName) {
		String htmlFile = realPath + DEFAULT_HTML_PATH + templateName + "_" + Calendar.getInstance().getTimeInMillis() + ".html";
		File file = new File(htmlFile);
		File parent = file.getParentFile();
        if(!parent.exists()){
        	parent.mkdirs();
		}
		Writer writer = null;
        try {
        	writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
            writer.write(html);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        	if (writer != null) {
        		try {
					writer.close();
				} catch (IOException e) {}
			}
		}
		return htmlFile;
	}
	
}
